package com.bdqn.shiro.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.shiro.pojo.Role;
import com.bdqn.shiro.pojo.User;
import com.bdqn.shiro.service.RoleService;
import com.bdqn.shiro.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    private UserService service;
    @Resource
    private RoleService roleService;

    @RequestMapping("user/list")
    public String toList(Model model, String usrName, Long roleId, @RequestParam(defaultValue = "1") Long pageIndex) {
        List<Role> role = roleService.list();
        Page page = new Page();
        page.setCurrent(pageIndex);
        User user = new User();
        user.setUsrName(usrName);
        user.setUsrRoleId(roleId);
        IPage iPage = service.getPage(page, user);
        model.addAttribute("roles", role);
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        model.addAttribute("userPager", iPage);
        return "user/list";
    }

    @GetMapping("user/add")
    public String toAdd(Model model) {
        List<Role> role = roleService.list();
        model.addAttribute("roles", role);
        return "user/add";
    }

    @PostMapping("user/doAdd")
    public String doAdd(User user) {
        user.setUsrPassword(service.save(user.getUsrPassword()));
        boolean bo = service.save(user);
        if (bo) {
            return "redirect:list";
        }
        return "user/add";
    }

    @GetMapping("user/edit")
    @RequiresPermissions("L060104") // Shiro注解判断有"L060104"才能访问该方法
    public String toEdit(Model model, Integer usrId) {
        User user = service.getById(usrId);
        List<Role> role = roleService.list();
        model.addAttribute("roles", role);
        model.addAttribute("sysUser", user);
        return "user/edit";
    }

    @PostMapping("user/save")
    public String doSave(User user) {
        user.setUsrPassword(service.save(user.getUsrPassword()));
        boolean bo = service.updateById(user);
        if (bo) {
            return "redirect:list";
        }
        return "user/edit";
    }

    @GetMapping("user/del/{usrId}")
    @ResponseBody
    public Map doDel(@PathVariable("usrId") Integer usrId) {
        boolean bo = service.removeById(usrId);
        Map map = new HashMap();
        if (bo) {
            map.put("result", "true");
        }
        return map;
    }


}
